public class Solution4 {
    //1049. 最后一块石头的重量 II
    public int lastStoneWeightII(int[] stones) {
        int n = stones.length;
        int sum = 0;
        for (int stone : stones) {
            sum += stone;
        }
        int value = sum / 2;
        int[][] dp = new int[n+1][value+1];//dp[i][j]就表示在[0,i]区间内选取总和不超过j的最大和
        for (int i = 1; i < n+1; i++) {
            for (int j = 1; j < value+1; j++) {
                dp[i][j] = dp[i-1][j];
                if (j >= stones[i-1]) {
                    dp[i][j] = Math.max(dp[i][j],dp[i-1][j-stones[i-1]]+stones[i-1]);
                }
            }
        }

        return sum - 2 * dp[n][value];
    }
}
